<!--直播间页面-->
<template lang="pug">
  kalix-master
    div.main1.center-box
      div.float
        img(src="../../../static/LivePic/u120.png" height="50" width="50")
      div.float.live-room
        div.live-top
          p {{this.routerName.liveName}}
        div.live-bottom
          p.float {{this.routerName.userName}}
          p.float {{this.routerName.type}}
          p.float 观看人数 {{this.liveNum}}
          div(@click="btnCollection" :class='this.isShow == true?"gray":"green"').shoucang {{txt}}
          div.clear
      div.clear
    div.main2.center-box
      div.video.float
        div
          LiveVideo(v-if="videoConfig.videoSrc"
          :videoSrc="videoConfig.videoSrc"
          :width="videoConfig.videoWidth"
          :height="videoConfig.videoHeight"
          :text = "videoConfig.danmuContent"
          ref="danmuSubmit")
      div.chat-room
        div.nav
          div.float(v-for="(text, key) in textArray" @click="visit(text,key)" :class='key==selected?"bg-recover":""') {{text}}
          div.clear
        div.chat-content
          div.answer(v-if="selected===0")
            div.answer-content(ref="arrPush")
              div.quiz-person(v-for="(item, index) in redata")
                p.name.float {{item.sender}}：
                p.quiz-content.float {{item.message}}
                div.clear
            div.quiz()
              input(type="text" placeholder="请输入问题内容" v-model="videoConfig.danmuContent" @keyup.enter="send" maxlength="53")
              button(@click="send" ref="faSong" v-show="time === 'in'").send 发送
              button(ref="faSongs" v-show="time === 'out'").noSend {{jiShi}}
          div.lesson(v-if="selected===1")
            h1 课程名称
            p.teacher 授课教师
            div
              span.strong 课时：
              span 12课时
            div
              span.strong 学分：
              span 3.0
            div
              div.float.strong 课程简介：
              div.float.detail 啥傲娇少女的你你啥都没说的妈二房的法庭甘为人梯二投入到
              div.clear
          div.teacher-intro(v-if="selected===2")
            div.teacher-top
              div.float
                img(src="../../../static/LivePic/u120.png" height="70" width="70")
              div.introduce.float
                div.intro-top
                  p {{this.routerName.userName}}
                div.intro-bottom
                  p.float 职称
                  p.float 学历
                  div.clear
              div.clear
            div.teacher-bottom
              div.strong.float 教师简介：
              div.float.detail asdfasdfasdf asasfasdfasdf aef asdf asd fasdf asdf awefasdfawef
              div.clear
      div.clear
</template>
<script>
  import Message from '../../components/Layout/message'
  export default {
    data() {
      return {
        websock: null,
        isActive: false,
        isvisit: false,
        selected: 0,
        isShow: true,
        txt: null,
        liveNum: 0,
        jiShi: 5,
        routerName: {},
        timer: '',
        time: 'in',
        lockReconnect: false, // 是否真正建立连接
        timeout: 28 * 1000, // 30秒一次心跳
        timeoutObj: null, // 心跳心跳倒计时
        serverTimeoutObj: null, // 心跳倒计时
        timeoutnum: null, // 断开 重连倒计时
        textArray: [
          '在线答疑',
          '课程简介',
          '教师简介'
        ],
        answer: true,
        redata: [],
        videoConfig: {
          videoSrc: '',
          danmuContent: '',
          videoWidth: '870',
          videoHeight: '570'
        },
        uid: null,
        collectId: null,
        xingxing: [],
        fl: true,
        exp: /草|原|傻|逼|fuck/g,
        xing: 0
      }
    },
    mounted() {
      this.uid = this.$KalixCatch.get('id')
      this.routerName = JSON.parse(window.sessionStorage.getItem('par'))
      this.videoConfig.videoSrc = JSON.parse(window.sessionStorage.getItem('par')).liveUrl
      this.getCollect()
    },
    created() {
      this.initWebSocket()
    },
    destroyed() {
      this.websock.close() // 离开路由之后断开websocket连接
    },
    methods: {
      getCollect() { // 获取收藏状态
        if (this.uid != null) {
          let jsonStr = {'userId': this.uid, 'teacherId': this.routerName.userId}
          this.axios.request({
            method: 'GET',
            url: '/camel/rest/user/collects',
            params: {
              jsonStr: jsonStr
            }
          }).then(res => {
            console.log('res-getCollect===============', res.data)
            if (res.data.totalCount > 0) {
              this.collectId = res.data.data[0].id
              this.isShow = false
            }
            this.txt = this.isShow ? '收藏' : '已收藏'
          })
        }
      },
      jiShiQi() {
        this.fl = false
        this.timer = setInterval(() => {
          if (this.jiShi > 0) {
            this.jiShi = this.jiShi - 1
            if (this.jiShi === 0) {
              this.time = 'in'
              this.fl = true
              clearInterval(this.timer)
            }
          }
        }, 1000)
        if (this.jiShi === 0) {
          this.jiShi = 5
        }
      },
      visit(text, key) {
        this.isvisit = true
        this.selected = key
      },
      btnCollection() {
        if (this.isShow) {
          if (this.uid == null) {
            Message.warning('请登录后收藏！')
            this.isShow = true
          } else {
            this.axios.request({
              method: 'POST',
              url: '/camel/rest/user/collects',
              data: {
                teacherId: this.routerName.userId,
                userId: this.uid
              }
            }).then(res => {
              if (res.data.success) {
                console.log('收藏成功---------------------:')
                Message.success(res.data.msg)
                this.isShow = false
              } else {
                Message.error(res.data.msg)
              }
              this.txt = this.isShow ? '收藏' : '已收藏'
            })
          }
        } else {
          this.getCollect()
          this.$confirm('确定取消收藏吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.axios.request({
              method: 'DELETE',
              url: '/camel/rest/user/collects/' + this.collectId,
              params: {
                id: this.collectId
              }
            }).then(res => {
              if (res.data.success) {
                console.log('取消收藏成功---------------------:')
                Message.success(res.data.msg)
                this.isShow = true
              } else {
                Message.error(res.data.msg)
              }
              this.txt = this.isShow ? '收藏' : '已收藏'
            })
          })
        }
        // this.txt = this.isShow ? '收藏' : '已收藏'
      },
      initWebSocket() { // 初始化weosocket
        const wsuri = 'ws://127.0.0.1:8181/training-websocket/chat/' + JSON.parse(window.sessionStorage.getItem('par')).id
        this.websock = new WebSocket(wsuri)
        this.websock.onmessage = this.websocketonmessage
        this.websock.onopen = this.websocketonopen
        this.websock.onerror = this.websocketonerror
        this.websock.onclose = this.websocketclose
      },
      // 重新连接
      reconnect() {
        var that = this
        if (that.lockReconnect) {
          return
        };
        that.lockReconnect = true
        // 没连接上会一直重连，设置延迟避免请求过多
        that.timeoutnum && clearTimeout(that.timeoutnum)
        that.timeoutnum = setTimeout(function () {
          // 新连接
          that.initWebSocket()
          that.lockReconnect = false
        }, 5000)
      },
      reset() { // 重置心跳
        var that = this
        // 清除时间
        clearTimeout(that.timeoutObj)
        clearTimeout(that.serverTimeoutObj)
        // 重启心跳
        that.start()
      },
      start() { // 开启心跳
        var self = this
        self.timeoutObj && clearTimeout(self.timeoutObj)
        self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
        self.timeoutObj = setTimeout(function() {
          // 这里发送一个心跳，后端收到后，返回一个心跳消息，
          if (self.websock.readyState === 1) { // 如果连接正常
            self.websock.send('heartCheck')
          } else { // 否则重连
            self.reconnect()
          }
          self.serverTimeoutObj = setTimeout(function() {
            // 超时关闭
            self.websock.close()
          }, self.timeout)
        }, self.timeout)
      },
      websocketonopen() { // 连接建立之后执行send方法发送数据
        if (this.xing === 0) {
          this.websocketsend('{"message": "加入直播间", "sender":"小白", "received":""}')
        }
        this.xing += 1
      },
      websocketonerror() { // 连接建立失败重连
        this.initWebSocket()
        this.reconnect()
      },
      websocketonmessage(e) { // 数据接收
        const redata = JSON.parse(e.data)
        this.redata.push(redata)
        this.$refs.danmuSubmit.newDanmu(redata.message)
      },
      websocketsend(Data) { // 数据发送
        this.websock.send(Data)
      },
      websocketclose(e) { // 关闭
        console.log('断开连接', e)
        this.reconnect()
        this.websocketsend(' ')
      },
      send() {
        if (this.fl) {
          if (this.videoConfig.danmuContent != null && this.videoConfig.danmuContent !== '') {
            this.time = 'out'
            this.videoConfig.danmuContent = this.videoConfig.danmuContent.replace(this.exp, '*')
            this.websocketsend('{"message": "' + this.videoConfig.danmuContent + '", "sender":"小白", "received":""}')
            this.videoConfig.danmuContent = ''
            var minArrPush = this.$refs.arrPush
            setTimeout(() => {
              minArrPush.scrollTop = minArrPush.scrollHeight
            }, 10)
            this.jiShiQi()
          }
          if (this.videoConfig.danmuContent === this.xingxing) {
          }
        }
      }
    }
  }
</script>

<style scoped lang="stylus">
  .float
    float left

  .clear
    clear both

  img
    display block

  .center-box
    width: 1200px
    margin: 0 auto

  .main1
    margin-top 25px

  .live-room
    margin-left 15px
    width 1100px

  .live-top
    font-size 18px
    font-weight 400

  .live-bottom
    margin-top 8px
    p
      font-size 14px
      color #999
      margin-right 30px
      line-height 25px
    button
      display block
      float right
      width 110px
      height 25px
      border-radius 12.5px
      border none
      background-color rgb(0, 143, 149)
      outline none
      cursor pointer
      color white

  .main2
    margin-top 10px
    margin-bottom 150px

  .video
    width 870px
    height 570px

  .chat-room
    float right
    width 330px

  .nav
    .float
      width 110px
      height 40px
      text-align center
      line-height 40px
      font-size 14px
      background-color: rgba(238, 238, 238, 1)
      cursor pointer
      color #666

  /*.float:hover*/
  /*background-color #fff*/
  .bg-recover
    background-color #fff !important

  .answer
    height 516px
    background-color #F5F5F5

  .answer-content
    font-size 12px
    line-height 20px
    height 482px
    overflow-y auto
    overflow-x hidden

  /*display flex*/
  /*flex-direction column-reverse*/

  .name
    margin-left 18px
    color #008F95

  .quiz-content
    width 265px
    border-radius 1px
    color #999
    padding 0 2px
    box-sizing border-box
    word-wrap break-word
    word-break break-all
    overflow: hidden

  .quiz
    width 330px
    border 1px solid rgb(204, 204, 204)
    height 48px
    position relative
    box-sizing border-box
    input
      height 29px
      margin-top 6.5px
      border-radius 5px 0px 0px 5px
      width 238px
      padding-left 10px
      margin-left 8px
      outline none
    button
      background-color rgb(0, 143, 149)
      color #fff
      width 60px
      height 35px
      border none
      cursor pointer
      border-radius 0 5px 5px 0
      position absolute
      top 5px
      right 5px

  .lesson
    padding-top 18px
    padding-left 18px
    color #999
    font-size 14px
    h1
      font-size 18px
      font-weight 700
      line-height 36px
    .teacher
      line-height normal

  .strong
    font-weight 700
    line-height normal

  .detail
    width 242px
    line-height normal

  .introduce
    margin-left 14px

  .teacher-intro
    padding-top 20px
    color #999

  .teacher-top
    width fit-content
    margin 0 auto

  .intro-top
    font-size 16px
    font-weight 700
    line-height 40px

  .intro-bottom
    font-size 14px
    .float
      margin-right 5px

  .teacher-bottom
    margin-top 10px
    margin-left 18px
    font-size 14px

  .shoucang
    float right
    width 80px
    height 30px
    line-height 30px
    text-align center
    color #fff
    /*background-color #008F95 !important*/
    border-radius 5px
    cursor pointer
    user-select none

  .gray
    background-color #008F95

  .green
    background-color #595959

  .quiz .send
    z-index 20

  .quiz .noSend
    background-color #ccc

  .quiz-person
   margin 5px 0

</style>
